package com.yanzhen.service;

import com.github.pagehelper.PageHelper;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.yanzhen.entity.Admin;
import com.yanzhen.mapper.AdminDao;
import com.yanzhen.utils.BeanMapUtils;
import com.yanzhen.utils.MapParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional  //事务控制
public class AdminService {
    @Autowired
    private AdminDao adminDao;
    //    新增成功返回值
    public int create(Admin pi){
        return adminDao.create(pi);
    }
    //   mybatis中万能的map
    public int delete(Integer id){
        Map<String,Object> paramMap = Maps.newHashMap(); //谷歌的guava包
                paramMap.put("id",id);
        return adminDao.delete(paramMap);
    }
    public int deleteBatch(String ids){
//        前端传来的是11,22,33这种字符串
        int flag = 0;
        List<String> list = Splitter.on(",").splitToList(ids);//谷歌插件的方法  切割掉 , 然后存放在list集合中
        for (String s : list) {
            adminDao.delete(MapParameter.getInstance().addId(Integer.parseInt(s)).getMap());  //循环调用
            flag++;
        }
        return flag;
    }

    public int update(Admin admin){
//        传入的admin对象直接转换成map集合
        Map<String, Object> map = BeanMapUtils.beanToMapForUpdate(admin);
        map.put("id",admin.getId());
        return adminDao.update(map);
    }
    //查询
    public List<Admin> query(Admin admin){
//        调用插件进行分页
        PageHelper.startPage(admin.getPage(),admin.getLimit());
        Map<String, Object> map = BeanMapUtils.beanToMap(admin);
        return adminDao.query(map);
    }
    //明细
    public Admin detail(Integer id){
        Map<String,Object> paramMap = Maps.newHashMap();
        paramMap.put("id",id);
        return adminDao.detail(paramMap);
    }
    //配合去分页
    public int count(Admin admin){
        Map<String, Object> map = BeanMapUtils.beanToMap(admin);
        return adminDao.count(map);
    }
    /**
     * 管理员登录
     * @param account
     * @param password
     * @return
     */
    public Admin login(String account,String password){
        Map<String, Object> map = MapParameter.getInstance().add("account",account).add("password",password).getMap();
        return adminDao.detail(map);
    }
}
